package cn.wmw.xyy.mq;

import cn.wmw.xyy.domain.Course;
import cn.wmw.xyy.domain.MessageSms;
import cn.wmw.xyy.domain.User;
import cn.wmw.xyy.service.IMessageSmsService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "course-message-group",
        topic = "course-topic",
        selectorExpression = "sendMessage-tag"
)
public class CourseSendMessageConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IMessageSmsService messageSmsService;

    @Override
    public void onMessage(MessageExt messageExt) {
        // 1.转换数据
        byte[] body = messageExt.getBody();
        if (body == null || body.length == 0){
            log.error("课程信息推送失败，消息内容为空！");
            return;
        }
        String jsonStr = new String(body, StandardCharsets.UTF_8);
        Course course = JSON.parseObject(jsonStr, Course.class);
        // 2.准备发送的内容
        String message = "亲爱的用户您好，最新课程 <a href='localhost:6002/detail.html?courseId="+course.getId()+"'> "+course.getName()+" </a> 发布啦，点击课程了解详情";
        // 3.准备要发送的用户信息，要根据发送用户维度去查询用户
        List<User> users = Arrays.asList(new User(1L, "131555555555"),
                new User(2L, "131555554444"),
                new User(3L, "131555557777"));
        //sendMessageEmail(message, users);
        sendMessageSms(message, users);
        //sendMessageStation();
    }

    private void sendMessageSms(String message, List<User> users) {
        // 1.发送短信
        users.forEach(e->{
            // @TODO 1.发送短信
            log.info(message + ":" + e.getId());
            // 2.保存发送日志到数据库
            MessageSms messageSms = new MessageSms();
            messageSms.setTitle("课程发布");
            messageSms.setContent(message);
            messageSms.setSendTime(new Date());
            messageSms.setUserId(e.getId());
            messageSmsService.insert(messageSms);
        });
    }
}
